package org.example.service;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

public class RpcEncoder extends MessageToByteEncoder {

    private Class<?> clazz;

    private Serializer serializer;


    public RpcEncoder(Class<?> clazz, Serializer serializer) {

        this.clazz = clazz;

        this.serializer = serializer;

    }


    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, Object msg, ByteBuf byteBuf) throws Exception {

        if (clazz != null && clazz.isInstance(msg)) {

            //使用json序列化将对象转换成byte
            byte[] bytes = serializer.serialize(msg);

            //写入消息长度，就是消息头信息
            byteBuf.writeInt(bytes.length);

            //消息体中包含了要发送的数据
            byteBuf.writeBytes(bytes);

        }

    }

}
